<template>
  <div class="register_container">
    <CommonBack :title="title"></CommonBack>
    <div class="register_box">
      <van-form @submit="onSubmit">
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="请输入用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password1"
          type="password"
          name="password1"
          label="密码"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-field
          v-model="password2"
          type="password"
          name="password2"
          label="确认密码"
          placeholder="请确认密码"
          :rules="[
            { required: true, message: '请填写密码' },
            { validator, message: '两次密码不一致' },
          ]"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >注册</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import CommonBack from "@/components/CommonBack.vue";
import { Toast } from 'vant';
export default {
  name: "Register",
  data() {
    return {
      title: "注册",
      username: "",
      password1: "",
      password2: "",
    };
  },
  methods: {
    firstCreate() {
      this.$store.commit("changeTabShow");
    },
    onSubmit(values) {
      let obj = {
        username:values.username,
        password:values.password1,
        token:this.newGuid()
      }
      // 设置 cookie
      Cookies.set(`${this.username}` , JSON.stringify(obj) , { expires: 7 })
      Toast.success('注册成功')
      setTimeout(() => {
        this.$router.push({
          path:'/login'
        })
        Toast.clear()
      }, 1000)
    },
    validator(val) {
      if (val !== this.password1 && this.password1 !== "") {
        return false;
      } else {
        return true;
      }
    },
    // 随机生成token
    newGuid() {
      var guid = "";
      for (var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
        if (i == 8 || i == 12 || i == 16 || i == 20) guid += "-";
      }
      return guid;
    },
  },
  created() {
    // Cookies.remove('lls')
    this.firstCreate();
  },
  destroyed() {
    this.$store.commit("changeTabShow");
  },
  components: { CommonBack },
};
</script>

<style lang="less" scoped>
.register_box {
  padding-top: 46px;
  /deep/ .van-cell {
    position: relative;
    margin: 15px 0px;
    overflow: visible;
    &::after {
      bottom: 8px;
    }
    .van-field__error-message {
      position: absolute;
      left: 0px;
      bottom: -25px;
    }
  }
}
</style>